package com.oscar.ehome.view.pageview;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesActivity;
import com.oscar.ehome.bean.UsersBean;
import com.oscar.ehome.bean.loginbean.UserBean;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.provider.gildeimage.GildeUtils;
import com.oscar.ehome.utils.basethem.TintManager;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.CreateCodeImgUtils;
import com.oscar.ehome.utils.util.PermissionUtil;
import com.oscar.ehome.utils.util.ToastUtil;
import com.oscar.ehome.view.loginview.ApproveActivity;
import com.oscar.ehome.view.loginview.CaptureActivity;
import com.oscar.ehome.view.messageview.MessageDetilActivity;
import com.oscar.ehome.view.setview.SigninActivity;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.content.ContentValues.TAG;

/**
 * Created by oscar
 * author: MengWanhe
 * date: On 2017/7/6
 * 增员页面
 */

public class AddMemberActivity extends BasesActivity implements EasyPermissions.PermissionCallbacks {

    /**
     * 返回
     */
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    /**
     * 返回
     */
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    /**
     * 标题
     */
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    /**
     * 头像
     */
    @BindView(R.id.member_head_img)
    ImageView memberHeadImg;
    /**
     * 姓名
     */
    @BindView(R.id.member_name)
    TextView memberName;
    /**
     * 职级
     */
    @BindView(R.id.member_leve)
    TextView memberLeve;
    /**
     * 二维码
     */
    @BindView(R.id.er_code_img)
    ImageView erCodeImg;
    /**
     * 保存图片
     */
    @BindView(R.id.share_saveimg_layout)
    RelativeLayout shareSaveimgLayout;
    /**
     * 分享链接
     */
    @BindView(R.id.share_img_layout)
    RelativeLayout shareImgLayout;
    /**
     * 性别
     */
    @BindView(R.id.sex_img)
    ImageView sexImg;
    /**
     * title布局
     */
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;

    UserBean userBean;//登录的所有信息
    UsersBean usersBean;//个人信息
    @BindView(R.id.tv_twocode_show)
    TextView tvTwocodeShow;
    private String twocode;

    //分享
    private ShareAction shareAction;
    private String url = "";//分享链接
    Bitmap bitmap;//二维码图片


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addmember);
        ButterKnife.bind(this);
        setColor();
        twocode = getIntent().getExtras().getString("twocode", "");
        isPressmion();
        initView();
    }


    /**
     * 设置颜色
     */
    public void setColor() {
        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getColor()));
        TintManager.setTint(shareSaveimgLayout, Color.parseColor(SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getColor()));
        TintManager.setTint(shareImgLayout, Color.parseColor(SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getColor()));
    }

    /**
     * 初始化数据
     */
    public void initView() {
        titleImgBack.setVisibility(View.VISIBLE);
        titleImgBack.setImageResource(R.mipmap.fanhui);

        String user = SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getUserBean();
        if (user != null) {
            userBean = new Gson().fromJson(user, UserBean.class);
        }
        String users = SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getUserMessage();
        if (users != null) {
            usersBean = new Gson().fromJson(users, UsersBean.class);
        }

        if (twocode.equals("twocode")) {
            titleTopbar.setText(getString(R.string.mine_two_code));
            tvTwocodeShow.setText(getString(R.string.mine_twocode_show));
            shareSaveimgLayout.setVisibility(View.GONE);
            shareImgLayout.setVisibility(View.GONE);
            if (userBean.getId() != null || !(userBean.getId().equals(""))) {
                try {
                    Resources r = this.getResources();
                    Bitmap bit_logo = BitmapFactory.decodeResource(r, R.mipmap.ehomelogefour);
                    Bitmap bitmaps = CreateCodeImgUtils.createCode(userBean.getId(),bit_logo);


                    bitmap = CreateCodeImgUtils.addLogo(bitmaps, bit_logo);
                    erCodeImg.setImageBitmap(bitmaps);
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
        } else {
            titleTopbar.setText(getString(R.string.mine_add_people));
            if (userBean.getExclusiceSrc() != null) {
                try {
                    url = C.ip + userBean.getExclusiceSrc();
                    Bitmap bit = CreateCodeImgUtils.Create2DCode(url);
                    Resources r = this.getResources();
                    Bitmap bit_logo = BitmapFactory.decodeResource(r, R.mipmap.ehomelogefour);
                    bitmap = CreateCodeImgUtils.addLogo(bit, bit_logo);
                    erCodeImg.setImageBitmap(bitmap);
                } catch (WriterException e) {
                    e.printStackTrace();
                }
            }
        }
        if (usersBean != null)
            if (usersBean.getSex() != null) {
                if (usersBean.getSex().equals("女")) {
                    sexImg.setImageResource(R.mipmap.nv);
                } else if (usersBean.getSex().equals("男")) {
                    sexImg.setImageResource(R.mipmap.nan);
                }
            }
        if (usersBean.getName() != null) {
            memberName.setText(usersBean.getName());
        } else {
            if (SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getUsername() != null) {
                memberName.setText(SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getUsername());
            }
        }
        if (usersBean.getRoleMobile() != null) {
            memberLeve.setText(usersBean.getRoleMobile().getRoleName());
        } else {
            memberLeve.setText("暂无");
        }
        if (usersBean.getPhoto() != null) {
            String img_path = usersBean.getPhoto();
            GildeUtils.loadUrlImage4(C.qiniu_ip + img_path, memberHeadImg, AddMemberActivity.this);
        } else {
            if (SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getUserimg() != null) {
                String img_path = SystemConfigFactory.getInstance(AddMemberActivity.this).getSystemConfig().getUserimg();
                GildeUtils.loadUrlImage4(C.qiniu_ip + img_path, memberHeadImg, AddMemberActivity.this);
            }
        }
    }


    @OnClick({R.id.title_layout_left, R.id.share_saveimg_layout, R.id.share_img_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_layout_left://返回
                finish();
                break;
            case R.id.share_saveimg_layout://保存图片
                if (PermissionUtil.getSdPremission(AddMemberActivity.this) && PermissionUtil.getSdreadPremission(AddMemberActivity.this)) {
                    saveImage(bitmap);
                } else {
                    ToastUtil.show(AddMemberActivity.this, "请开启手机读写权限！");
                    isPressmion();
                }
                break;
            case R.id.share_img_layout://分享链接
//                Intent sendIntent = new Intent();
//                sendIntent.setAction(Intent.ACTION_SEND);
//                File f = new File("/storage/emulated/0/video/1515157613719.pdf");
//                sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
//                sendIntent.setType("*/*");
//              sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");//微信朋友
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qqfav.widget.QfavJumpActivity");//保存到QQ收藏
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qlink.QlinkShareJumpActivity");//QQ面对面快传
//          sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.qfileJumpActivity");//传给我的电脑
                //sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");//QQ好友或QQ群
//          sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");//微信朋友圈，仅支持分享图片
//                startActivity(sendIntent );

                openShare();
                break;
        }
    }

    /**
     * 打开分享面板
     */
    public void openShare() {
        UMImage thumb = new UMImage(AddMemberActivity.this, R.mipmap.ehomelogo);
        shareAction = new ShareAction(AddMemberActivity.this)
                .setDisplayList(SHARE_MEDIA.SINA, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE, SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE)
                .withMedia(new UMWeb(url, getString(R.string.juxng_title), userBean.getName() + "诚邀您加入" + userBean.getCompany().getName() + "集团，携手开启创业新纪元。", thumb))
                .setCallback(umShareListener);
        shareAction.open();

    }

    private UMShareListener umShareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            Toast.makeText(AddMemberActivity.this, "分享成功", Toast.LENGTH_LONG).show();
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            if (t.getMessage().contains("2008")) {
                Toast.makeText(AddMemberActivity.this, "分享失败,请检查是否安装应用！", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(AddMemberActivity.this, "分享失败", Toast.LENGTH_LONG).show();
            }
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(AddMemberActivity.this, "分享取消", Toast.LENGTH_LONG).show();

        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
//        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
//        if (ssoHandler != null) {
////            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//        }
    }

    /**
     * 保存图片
     */
    public void saveImage(Bitmap bit) {
        // 首先保存图片
        File f = new File(Environment.getExternalStorageDirectory().getPath(), "erCode" + ".jpg");
        if (f.exists()) {
            f.delete();//先删除在添加
        } else {
            f.mkdirs();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            boolean isSuccess = bit.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            if (isSuccess) {
                ToastUtil.show(AddMemberActivity.this, "保存成功！");
            } else {
                ToastUtil.show(AddMemberActivity.this, "保存失败，请开启手机读写权限");
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //把文件插入到系统图库
        MediaStore.Images.Media.insertImage(getContentResolver(), bit, "ercode", "xcc");

        //保存图片后发送广播通知更新数据库
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(f);
        intent.setData(uri);
        sendBroadcast(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    /**
     * 查看是否是6。0以上系统
     */
    public void isPressmion() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT >= 23) {
            if (EasyPermissions.hasPermissions(this, perms)) {//检查是否获取该权限
            } else {
                //第二个参数是被拒绝后再次申请该权限的解释
                //第三个参数是请求码
                //第四个参数是要申请的权限
                EasyPermissions.requestPermissions(this, "将要开启读取权限！", 0, perms);
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this, "为了您能保存图片，请开启手机读写权限！")
                    .setTitle("提示")
                    .setPositiveButton("去设置")
                    .setNegativeButton("取消", null)
                    .setRequestCode(0)
                    .build()
                    .show();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
}
